from models import SessionLocal, User, Book, Word, UserRole
from app import get_password_hash
from datetime import datetime

def init_db():
    db = SessionLocal()

    try:
        # 创建默认管理员用户
        admin_password = get_password_hash("1")
        print(f"Generated admin password hash: {admin_password}")  # 调试信息

        admin_user = User(
            username="admin",
            password=admin_password,
            email="admin@example.com",
            role=UserRole.ADMIN.value,
            is_active=True,
            created_at=datetime.utcnow()
        )

        # 检查是否已存在管理员用户
        existing_admin = db.query(User).filter(User.username == "admin").first()
        if existing_admin:
            print("Admin user already exists")
            # 更新管理员密码
            existing_admin.password = admin_password
            db.commit()
            print("Updated admin password")
        else:
            db.add(admin_user)
            db.commit()
            print("Created new admin user")

        # 创建示例书本
        book1 = Book(
            name="基础词汇",
            description="适合初学者的基础词汇"
        )
        book2 = Book(
            name="进阶词汇",
            description="适合中级学习者的词汇"
        )
        db.add_all([book1, book2])
        db.commit()

        # 添加示例单词
        words = [
            Word(
                word="detach",
                book_id=book1.id
            ),
            Word(
                word="anguish",
                book_id=book1.id
            ),
            # 可以继续添加更多单词...
        ]
        db.add_all(words)
        db.commit()

    except Exception as e:
        print(f"Error during initialization: {str(e)}")
        db.rollback()
        raise
    finally:
        db.close()

if __name__ == "__main__":
    init_db()